﻿/***************************************
 * 
 *  Creat By Ternence
 * 
 *  Creat Time 2016-03-21
 *  
 *  Describe 圆形按钮
 * ************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace NF_Tools
{
    public partial class BF_RoundButton : Button
    {
        public BF_RoundButton()
        {
            InitializeComponent();

            SetStyle(ControlStyles.SupportsTransparentBackColor, true);
            SetStyle(ControlStyles.Opaque, true);
            SetStyle(ControlStyles.ResizeRedraw, true);
            this.BackColor = Color.Transparent;
        }

        public BF_RoundButton(IContainer container)
        {
            container.Add(this);

            InitializeComponent();
        }

        [System.Runtime.InteropServices.DllImport("gdi32")]
        private static extern IntPtr BeginPath(IntPtr hdc);
        [System.Runtime.InteropServices.DllImport("gdi32")]
        private static extern int SetBkMode(IntPtr hdc, int nBkMode);
        const int TRANSPARENT = 1;
        [System.Runtime.InteropServices.DllImport("gdi32")]
        private static extern IntPtr EndPath(IntPtr hdc);
        [System.Runtime.InteropServices.DllImport("gdi32")]
        private static extern IntPtr PathToRegion(IntPtr hdc);
        [System.Runtime.InteropServices.DllImport("gdi32")]
        private static extern int Ellipse(IntPtr hdc, int x1, int y1, int x2, int y2);
        [System.Runtime.InteropServices.DllImport("user32")]
        private static extern IntPtr SetWindowRgn(IntPtr hwnd, IntPtr hRgn, bool bRedraw);
        [System.Runtime.InteropServices.DllImport("user32")]
        private static extern IntPtr GetDC(IntPtr hwnd);

        protected override void OnPaint(PaintEventArgs pevent)
        {
            base.OnPaint(pevent);

            IntPtr dc;
            IntPtr region;

            dc = GetDC(this.Handle);
            BeginPath(dc);
            SetBkMode(dc, TRANSPARENT);
            Ellipse(dc, 3, 3, this.Width - 3, this.Height - 3);
            EndPath(dc);
            region = PathToRegion(dc);
            SetWindowRgn(this.Handle, region, false);

            
        }

        protected override CreateParams CreateParams
        {
            get
            {
                const int WS_EX_TRANSPARENT = 0x20;
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= WS_EX_TRANSPARENT;
                return cp;
            }
        }
    }
}
